package com.code.train.gateway.util;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
public class JwtUtils {

    @Value("${train.jwt.member.timeout}")
    private Long timeoutConfig;

    @Value("${train.jwt.member.secret}")
    private String secretConfig;

    private static Long TOKEN_TIME_OUT;
    private static String TOKEN_SECRET;

    @PostConstruct
    public void init() {
        TOKEN_TIME_OUT = timeoutConfig;
        TOKEN_SECRET = secretConfig;
    }




    // 生成Token
    public static String getToken(Map params){
        long currentTime = System.currentTimeMillis();
        Key key = Keys.hmacShaKeyFor(TOKEN_SECRET.getBytes(StandardCharsets.UTF_8));
        return Jwts.builder()
                .signWith(key, SignatureAlgorithm.HS512) //加密方式
                .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000)) //过期时间戳
                .addClaims(params)
                .compact();
    }


    /**
     * 获取Token中的claims信息
     */
    public static Claims getClaims(String token) {
        return Jwts.parser()
                .setSigningKey(TOKEN_SECRET)
                .parseClaimsJws(token).getBody();
    }


    /**
     * 是否有效 true-有效，false-失效
     */
    public static boolean verifyToken(String token) {
        if (StrUtil.isBlank(token)) {
            log.warn("Token为空");
            return false;
        }

        try {
            Key key = Keys.hmacShaKeyFor(TOKEN_SECRET.getBytes(StandardCharsets.UTF_8));
            Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token); // 会自动验证签名和过期时间
            log.info("Token有效");
            return true;
        } catch (io.jsonwebtoken.ExpiredJwtException e) {
            log.warn("Token已过期: {}", e.getMessage());
        } catch (io.jsonwebtoken.SignatureException e) {
            log.warn("Token签名无效: {}", e.getMessage());
        } catch (Exception e) {
            log.warn("Token解析失败: {}", e.getMessage());
        }
        return false;
    }

}